//
//  RCNetwork.m
//  RCC_Project
//
//  Created by liwenbo on 16/3/16.
//  Copyright © 2016年 liwenbo. All rights reserved.
//

#import "YONetwork.h"

@implementation YONetwork

+ (AFHTTPSessionManager *)AFHTTPSessionManagerInit {
    AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    [manage.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manage.requestSerializer.timeoutInterval = 8.f;
    [manage.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    return manage;
}

+ (void)getWithURL:(NSString *)url
        withParams:(NSMutableDictionary *)params
  withSuccessBlock:(requestSuccessBlock)success
  withFailureBlock:(requestFailureBlock)failure {
    [self requestWithHTTPMethod:GET
                        withURL:url
                     withParams:params
               withSuccessBlock:success
               withFailureBlock:failure];
}


+ (void)postWithURL:(NSString *)url
         withParams:(NSMutableDictionary *)params
   withSuccessBlock:(requestSuccessBlock)success
   withFailureBlock:(requestFailureBlock)failure {
    [params setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersionName"];
    [params setObject:@"ios" forKey:@"appType"];
    [params setObject:[KeyChainStore load:@"KEY_USERNAME_PASSWORD"] forKey:@"appDeviceId"];
    [params setObject:[Utils genSign:params] forKey:@"appSign"];
    [self requestWithHTTPMethod:POST
                        withURL:url
                     withParams:params
               withSuccessBlock:success
               withFailureBlock:failure];
}

+ (void)patchWithURL:(NSString *)url
          withParams:(NSMutableDictionary *)params
    withSuccessBlock:(requestSuccessBlock)success
    withFailureBlock:(requestFailureBlock)failure {
    [self requestWithHTTPMethod:PATCH
                        withURL:url
                     withParams:params
               withSuccessBlock:success
               withFailureBlock:failure];
}

+ (void)deleteWithURL:(NSString *)url
           withParams:(NSMutableDictionary *)params
     withSuccessBlock:(requestSuccessBlock)success
     withFailureBlock:(requestFailureBlock)failure {
    [self requestWithHTTPMethod:DELETE
                        withURL:url
                     withParams:params
               withSuccessBlock:success
               withFailureBlock:failure];
}


+ (void)requestWithHTTPMethod:(HTTPMethod)httpMethod
                      withURL:(NSString *)url
                   withParams:(NSMutableDictionary *)params
             withSuccessBlock:(requestSuccessBlock)success
             withFailureBlock:(requestFailureBlock)failure {
    if (![self isNetWorkConnecting]) {
        DebugLog(@"网络好像断开了");
        return;
    }
    AFHTTPSessionManager *sessionManager = [self  AFHTTPSessionManagerInit];
    NSString *encodedString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    DebugLog(@"URL:%@",url);
    DebugLog(@"params:%@",params);
    if (httpMethod == GET) {
        [sessionManager GET:encodedString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            DebugLog(@"JSON: %@", result);
            success(dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DebugLog(@"Error: %@", error);
            failure(error);
        }];
    } else if (httpMethod == POST) {
        [sessionManager POST:encodedString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            DebugLog(@"JSON: %@", result);
            success(dic);
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DebugLog(@"Error: %@", error);
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }];
    } else if (httpMethod == PATCH) {
        [sessionManager PATCH:encodedString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            DebugLog(@"JSON: %@", result);
            success(dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DebugLog(@"Error: %@", error);
            failure(error);
        }];
    } else if (httpMethod == DELETE) {
        [sessionManager DELETE:encodedString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            DebugLog(@"JSON: %@", result);
            success(dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DebugLog(@"Error: %@", error);
            failure(error);
        }];
    }
}

+ (void)postImageWithURL:(NSString *)url
              withParams:(NSMutableDictionary *)params
               withImage:(UIImage *)images
        withSuccessBlock:(requestSuccessBlock)success
        withFailureBlock:(requestFailureBlock)failure {
    AFHTTPSessionManager *sessionManager = [self  AFHTTPSessionManagerInit];
    DebugLog(@"URL:%@",url);
    DebugLog(@"params:%@",params);
    [params setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersionName"];
    [params setObject:@"ios" forKey:@"appType"];
    [params setObject:[KeyChainStore load:@"KEY_USERNAME_PASSWORD"] forKey:@"appDeviceId"];
    [params setObject:[Utils genSign:params] forKey:@"appSign"];
    [sessionManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *fileData = UIImageJPEGRepresentation(images, 1.0);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:[NSDate date]]];
        [formData appendPartWithFileData:fileData name:@"head" fileName:fileName mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        DebugLog(@"JSON: %@", dic);
        success(dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"Error: %@", error);
        failure(error);
    }];
}

//网络连接状态判断
+ (BOOL)isNetWorkConnecting
{
    struct sockaddr zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sa_len = sizeof(zeroAddress);
    zeroAddress.sa_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags =
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        printf("Error. Count not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible =isNetworkEnable;/*  网络指示器的状态： 有网络 ： 开  没有网络： 关  */
    });
    return isNetworkEnable;
}


@end
